import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../../common/api/index.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/routers/index.dart';
import '../../../../../common/style/index.dart';
import '../../../../../common/utils/index.dart';
import 'index.dart';


class SubjectReplyPage extends GetView<SubjectReplyController> {
  const SubjectReplyPage({Key? key}) : super(key: key);

  static Future<dynamic> open(String subjectId, {String replyParentId = '', String replyHint = ''}) async {
    return await Get.toNamed(O2OARoutes.appBBSSubjectReply,
        arguments: {'subjectId': subjectId, 'replyParentId': replyParentId, 'replyHint': replyHint});
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Column(
      children: [
        Expanded(flex: 1, child: replayContentView(context)),
        _bottomBarView(context)
      ],
    );
  }

  Widget replayContentView(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10.w),
      child: Obx(() => TextField(
        autofocus: true,
        focusNode: controller.replyInputNode,
        controller: controller.replyInputController,
        maxLines: 5,
        decoration: InputDecoration(
            isDense: true,
            hintText: controller.state.replyHintObs,
            hintStyle: Theme.of(context).textTheme.bodySmall,
            filled: true,
            fillColor: Theme.of(context).colorScheme.background,
            border: InputBorder.none),
        style: Theme.of(context).textTheme.bodyLarge,
        textInputAction: TextInputAction.done,
      )),
    );
  }

  Widget _bottomBarView(BuildContext context) {
    return Container(
        color: Theme.of(context).colorScheme.background,
        child: Column(
          children: [
            const Divider(height: 1, color: AppColor.borderColor),
            const SizedBox(height: 5),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const SizedBox(width: 8),
                IconButton(
                    onPressed: controller.takePhoto,
                    icon: Icon(Icons.camera_alt, size: 36.w)),
                const SizedBox(width: 8),
                IconButton(
                    onPressed: controller.addImage,
                    icon: Icon(Icons.image, size: 36.w)),
                const SizedBox(width: 8),
              ],
            ),
            _imageListView(context),
            const SizedBox(height: 5)
          ],
        ));
  }

  /// 显示图片区域
  Widget _imageListView(BuildContext context) {
    return Obx(() {
      if (controller.state.replyImageMap.isNotEmpty) {
        return SizedBox(
            height: 108.w,
            child: GridView.count(
              shrinkWrap: true,
              crossAxisCount: 4,
              mainAxisSpacing: 10.0, //设置上下之间的间距(Axis.horizontal设置左右之间的间距)
              crossAxisSpacing: 10.0, //设置左右之间的间距(Axis.horizontal设置上下之间的间距)
              childAspectRatio: 0.8, //设置宽高比
              children: controller.state.replyImageMap.values.map((element) {
                return GestureDetector(
                    onTap: () => controller.clickImageItem(element),
                    child: imageItemView(context, element));
              }).toList(),
            ));
      }
      return Container();
    });
  }

  Widget imageItemView(BuildContext context, ReplyImageItem item) {
    Image imageView;
    Map<String, String> headers = {};
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    Align loadingOrDelete;
    if (item.fileId != null && item.fileId!.isNotEmpty) {
      String imageUrl =
          BBSAssembleControlService.to.getBBSAttachmentURL(item.fileId!);
      imageView = Image(
          image: NetworkImage(imageUrl, headers: headers),
          height: 64.w,
          fit: BoxFit.fill);
      loadingOrDelete = Align(
          alignment: Alignment.topRight,
          child: Padding(
              padding: const EdgeInsets.all(5),
              child: Icon(Icons.do_not_disturb_on, color: Colors.red, size: 36.w)));
    } else {
      imageView = Image(
          image: FileImage(File(item.fileLocalPath!)),
          height: 64.w,
          fit: BoxFit.fill);

      loadingOrDelete = const Align(
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      );
    }
    return Stack(children: [
      Align(alignment: Alignment.center, child: imageView),
      loadingOrDelete
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SubjectReplyController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(title: Text('bbs_subject_reply_title'.tr), actions: [
            TextButton(
                onPressed: () => controller.replay(),
                child: Text('bbs_subject_reply_send'.tr,
                    style: AppTheme.whitePrimaryTextStyle))
          ]),
          body: SafeArea(
            child: _buildView(context),
          ),
        );
      },
    );
  }
}
